#ifndef PARSE_TYPE_H__
#define PARSE_TYPE_H__

#include <stdlib.h>
#include "parse-basic.h"
#include "token.h"
#include "../ast/type.h"

#if 0
import std.lib;
import parse-basic;
import token;
import ..ast.type;
#endif

struct Type* parseType(struct TokenList** source)
{
	if(*source == NULL) return NULL;

	struct Type* r = NULL;

	if((*source)->head->tag == KEYWORD_CHAR_TOKEN)
	{
		*source = (*source)->tail;
		r = allocateType(CHAR,NULL);
	}

	else if((*source)->head->tag == KEYWORD_INT_TOKEN)
	{
		*source = (*source)->tail;
		r = allocateType(INT,NULL);
	}

	else if((*source)->head->tag == KEYWORD_VOID_TOKEN)
	{
		*source = (*source)->tail;
		r = allocateType(VOID,NULL);
	}

	else if((*source)->head->tag == KEYWORD_ENUM_TOKEN)
	{
		*source = (*source)->tail;
		// parseName() may return NULL for anonymous enums
		r = allocateType(ENUM,parseName(source));
	}

	else if((*source)->head->tag == KEYWORD_STRUCT_TOKEN)
	{
		*source = (*source)->tail;
		// parseName() may return NULL for anonymous structs
		r = allocateType(STRUCT,parseName(source));
	}

	else if((*source)->head->tag == KEYWORD_UNION_TOKEN)
	{
		*source = (*source)->tail;
		// parseName() may return NULL for anonymous unions
		r = allocateType(UNION,parseName(source));
	}

	if(r == NULL) return NULL;

	// pointers are parsed here to avoid left recursion
	while(*source != NULL && (*source)->head->tag == STAR)
	{
		*source = (*source)->tail;
		r = allocateType(POINTER,r);
	}

	return r;
}

#endif
